import Taro from '@tarojs/taro'
import React, { Component } from 'react'
import { ScrollView } from '@tarojs/components'
import { convertPx, getWebRealPx } from '@UTILS/common'
import { NoContentEmpty } from '@COMPONENTS/Empty'

export default class List extends Component {
  static defaultProps = {
    refresherBackground: '#f4f4f4',
    refresherDefaultStyle: 'black',
    refresherEnabled: true,
    backgroundColor: '#f4f4f4',
    style: {},
    listHeaderHeight: 0,
  }

  state = {
    height: 500,
  }

  componentDidMount() {
    const { listHeaderHeight } = this.props
    Taro.getSystemInfo({
      success: res => {
        this.setState({
          height: res.windowHeight - getWebRealPx(listHeaderHeight)
        })
      }
    })
  }

  componentDidUpdate(prevProps) {
    const { listHeaderHeight } = this.props
    if (prevProps.listHeaderHeight !== listHeaderHeight) {
      Taro.getSystemInfo({
        success: res => {
          this.setState({
            height: res.windowHeight - getWebRealPx(listHeaderHeight)
          })
        }
      })
    }
  }

  isScrolling = false

  onEndReached = () => {
    const { onEndReached } = this.props
    if (this.isScrolling || !onEndReached) { return }
    this.isScrolling = true
    onEndReached()
    this.isScrolling = false
  }

  render() {
    const {
      children, refreshing, onRefresh, refresherBackground,
      refresherDefaultStyle, refresherEnabled, backgroundColor, style
    } = this.props
    const { height } = this.state
    const isEmpty = Array.isArray(children) && (children.length === 0 && !refreshing)

    return (
      <ScrollView
        onScrollToLower={this.onEndReached}
        lowerThreshold={100}
        scrollY
        style={{ height: convertPx(height), backgroundColor, ...style }}
        refresherEnabled={refresherEnabled}
        onRefresherRefresh={onRefresh}
        refresherTriggered={refreshing}
        refresherBackground={refresherBackground}
        refresherDefaultStyle={refresherDefaultStyle}
        className="list"
      >
        {isEmpty ? <NoContentEmpty /> : children}
      </ScrollView>
    )
  }
}
